const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors'); // 1. 引入cors
const path = require('path'); // 引入path模块
// 使用 dotenv 配置并直接指定路径
const dotenv = require('dotenv');
const envPath = path.resolve(__dirname, '../.env');
dotenv.config({ path: envPath });
console.log('尝试加载的 .env 文件路径:', envPath);
console.log('MONGO_URI:', process.env.MONGO_URI ? '已设置' : '未设置');

// 引入日志工具
const logger = require('./utils/logger');

const app = express();
const port = process.env.PORT || 3000; // 优先使用环境变量中的端口

// --- 核心中间件 ---
// 2. 使用cors中间件 - 解决跨域问题
// 配置CORS以允许来自内网穿透地址的请求
const corsOptions = {
  origin: [
    'http://localhost:5174',
    'http://127.0.0.1:5174', // 添加127.0.0.1支持
    'http://124.223.42.84:65174', // 你的内网穿透地址
    'http://localhost:5173',
    'http://localhost:3000'
  ],
  credentials: true,
  optionsSuccessStatus: 200
};
app.use(cors(corsOptions));

// 3. 使用express.json()中间件 - 解析请求体
// 讲解：这个中间件让我们的Express应用能够识别并处理传入的JSON格式数据（比如用户注册时POST的用户名和密码）。
app.use(express.json());

// 添加请求日志中间件
app.use((req, res, next) => {
    logger.info('REQUEST', `${req.method} ${req.url}`, {
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        timestamp: new Date().toISOString()
    });
    
    // 记录响应时间
    const start = Date.now();
    res.on('finish', () => {
        const duration = Date.now() - start;
        logger.info('RESPONSE', `${req.method} ${req.url} ${res.statusCode}`, {
            duration: `${duration}ms`,
            contentLength: res.get('Content-Length')
        });
    });
    
    next();
});

// 静态文件服务
app.use(express.static('public'));

// --- 数据库连接 ---
if (process.env.MONGO_URI) {
    mongoose.connect(process.env.MONGO_URI)
        .then(() => {
            logger.info('DATABASE', 'MongoDB connected successfully!');
        })
        .catch(err => {
            logger.error('DATABASE', 'MongoDB connection error:', err);
        });
} else {
    logger.warn('DATABASE', 'MongoDB URI not configured, running without database connection');
}

// 基础路由 - Hello World
app.get('/', (req, res) => {
    logger.route('ROOT', 'Serving index.html');
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 使用路由文件
logger.info('SERVER', 'Loading user routes');
app.use('/api/users', require('./routes/users'));

logger.info('SERVER', 'Loading knowledge points routes');
app.use('/api/knowledge-points', require('./routes/knowledgePoints'));

logger.info('SERVER', 'Loading audio routes');
app.use('/api/audio', require('./routes/audio'));

// 添加测试音频路由（无认证）
logger.info('SERVER', 'Loading test audio routes');
app.use('/api/audio-test', require('./routes/audio_test'));

// 添加AI路由
logger.info('SERVER', 'Loading AI routes');
app.use('/api/ai', require('./routes/ai'));

// 添加统一ASR路由
logger.info('SERVER', 'Loading Unified ASR routes');
app.use('/api/unified-asr', require('./routes/unifiedAsr'));

// 添加RAG路由
logger.info('SERVER', 'Loading RAG routes');
app.use('/api/rag', require('./routes/rag'));

// API路由 - 用户信息
app.get('/api/user', (req, res) => {
    logger.route('USER_INFO', 'Fetching user information');
    const userInfo = {
        id: 1,
        name: '张三',
        email: 'zhangsan@example.com',
        role: '学生',
        joinDate: '2024-01-15',
        learningProgress: {
            completedCourses: 5,
            totalPoints: 1250,
            currentLevel: '中级'
        }
    };
    res.json(userInfo);
});

// API路由 - 知识点列表
app.get('/api/knowledge', (req, res) => {
    logger.route('KNOWLEDGE_LIST', 'Fetching knowledge points list');
    const knowledgePoints = [
        { id: 1, title: 'JavaScript基础', category: '编程', difficulty: '初级' },
        { id: 2, title: 'Express框架', category: '后端', difficulty: '中级' },
        { id: 3, title: 'HTML/CSS', category: '前端', difficulty: '初级' }
    ];
    res.json(knowledgePoints);
});

// 启动服务器
app.listen(port, () => {
    logger.info('SERVER', `费曼学习平台服务器运行在 http://localhost:${port}`);
    logger.info('SERVER', `Feynman Platform backend is running at http://localhost:${port}`);
});